package com.jsgt.greekfire.ui.home.entrance.createwallet

import android.text.*
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.widget.CompoundButton
import android.widget.EditText
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.goToActivity
import com.fhx.core.utils.ActivityStackManager
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.base.BaseBackgroundActivity
import com.jsgt.greekfire.bean.YTWallet
import com.jsgt.greekfire.common.util.YTWalletUtils
import com.jsgt.greekfire.dao.model.IdentityBean
import com.jsgt.greekfire.dao.model.WalletBean
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import com.jsgt.greekfire.ui.main.MainAtrActivity
import kotlinx.android.synthetic.main.activity_register_wallet.*


/**
 * 创建钱包
 */
class RegisterWalletActivity : BaseBackgroundActivity() {
    private val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }

    private var ytWallet: YTWallet? = null


    override fun getLayoutId(): Int = R.layout.activity_register_wallet

    override fun onBackPressed() {
        super.onBackPressed()
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }

    override fun main() {
//        title = getString(R.string.wallet_create)

        next_step_tv.setOnClickListener {
            nextStep()
        }
        cb_eye.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (isChecked) {
                    wallet_security_pwd_et.transformationMethod =
                        HideReturnsTransformationMethod.getInstance()
                } else {
                    wallet_security_pwd_et.transformationMethod =
                        PasswordTransformationMethod.getInstance()
                }
                endSelection(wallet_security_pwd_et)
            }
        })
        cb_eye_confirm.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (isChecked) {
                    wallet_security_pwd_et_confirm.transformationMethod =
                        HideReturnsTransformationMethod.getInstance()
                } else {
                    wallet_security_pwd_et_confirm.transformationMethod =
                        PasswordTransformationMethod.getInstance()
                }
                endSelection(wallet_security_pwd_et_confirm)
            }
        })

        wallet_name_et.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(
                s: CharSequence, start: Int, before: Int,
                count: Int
            ) {
            }

            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int,
                after: Int
            ) {
            }

            override fun afterTextChanged(s: Editable) {
            }
        })

        walletViewModel.getAllIdentity()?.observe(this, Observer {
            if (it.isNotEmpty() && ytWallet != null) {
                it.forEach {it1->
                    if (it1.getPriKeyByAES() == ytWallet!!.getEcKeyPair().privateKey.toString()) {
                        val walletBean = WalletBean()
                        walletBean.key = "ATR"
                        walletBean.identityId = it1.id
                        walletBean.address = ytWallet!!.address
                        walletBean.name = "ATR"
                        walletViewModel.addWallet(walletBean)
                        return@forEach
                    }
                }
            }
        })

        walletViewModel.getAllWallet()?.observe(this, Observer {
            if (it != null && ytWallet != null) {
                it.forEach {it1->
                    if (it1.address == ytWallet!!.address) {
                        goToActivity<MainAtrActivity>()
                        ActivityStackManager.finishAll()
                    }
                }
            }
            showProgress(false)
        })
    }

    private fun nextStep() {
        next_step_tv.isEnabled = false
        showProgress(true)

        //钱包名称
        val identityName = wallet_name_et.text.toString().trim()

        //密码
        val securityPwd = wallet_security_pwd_et.text.toString().trim()
        // 确认密码
        val securityPwdConfirm = wallet_security_pwd_et_confirm.text.toString().trim()
        // 密码提示
        val pwdTips = wallet_tips_et.text.toString().trim()

        if (TextUtils.isEmpty(identityName) ||
            TextUtils.isEmpty(securityPwd) ||
            TextUtils.isEmpty(securityPwdConfirm)
        ) {
            ToastUtils.show(this, getString(R.string.input_all_info))
            next_step_tv.isEnabled = true
            showProgress(false)
            return
        }

        if (securityPwd != securityPwdConfirm) {
            ToastUtils.show(this, getString(R.string.wallet_safe_pwd_warning1))
            next_step_tv.isEnabled = true
            showProgress(false)
            return
        }

        if (securityPwd.length < 6) {
            ToastUtils.show(this, getString(R.string.wallet_safe_pwd_warning))
            next_step_tv.isEnabled = true
            showProgress(false)
            return
        }

        val identityBean = IdentityBean()
        identityBean.backup = false
        identityBean.identityName = identityName
        identityBean.setPasswordByMd5(securityPwd)
        identityBean.passwordTips = pwdTips

        ytWallet =
            YTWalletUtils.generateBip44Wallet(YTWalletUtils.getMnemonic(), identityBean.password)

        identityBean.setMnemonicByAES(ytWallet!!.getMnemonic())
        identityBean.setPriKeyByAES(ytWallet!!.getEcKeyPair().privateKey.toString())

        walletViewModel.addIdentity(identityBean)
    }

    /**
     * 设置EditText游标至末尾
     */
    fun endSelection(editText: EditText) {
        val text: Spannable? = editText.text
        if (text != null) {
            Selection.setSelection(text, text.length)
        }
    }
}